package com.yuanfeng.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.commoms.aspect.UserPermissionsResult;
import com.yuanfeng.commoms.aspect.UserService;
import com.yuanfeng.commoms.config.PermissionsConstant;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.ParseMapUtils;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.PinyinUtils;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.goods.dto.GoodsBrandDTO;
import com.yuanfeng.goods.entity.GoodsBrandCatEntity;
import com.yuanfeng.goods.entity.GoodsBrandEntity;
import com.yuanfeng.goods.entity.GoodsCommonEntity;
import com.yuanfeng.goods.mapper.GoodsBrandCatMapper;
import com.yuanfeng.goods.mapper.GoodsBrandMapper;
import com.yuanfeng.goods.mapper.GoodsCatMapper;
import com.yuanfeng.goods.mapper.GoodsCommonMapper;
import com.yuanfeng.goods.service.GoodsBrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Service
public class GoodsBrandServiceImpl extends ServiceImpl<GoodsBrandMapper, GoodsBrandEntity>
    implements GoodsBrandService{

    @Autowired
    private GoodsCommonMapper goodsCommonMapper;
    @Autowired
    private GoodsBrandCatMapper goodsBrandCatMapper;
    @Autowired
    private GoodsCatMapper goodsCatMapper;
    @Override
    public ResponseResult queryBrandGoods() {
        Map<String,Object> map=new HashMap<>();

        List<GoodsBrandEntity> goodsBrandList =this.baseMapper.selectList(new LambdaQueryWrapper<GoodsBrandEntity>());
        map.put("goodsBrandList",goodsBrandList);
        map.put("totalCount",goodsBrandList.size());
        return ResponseResult.success(map);
    }

    @Override
    public ResponseResult selectBrandName(Map<String, Object> map) {
        String brandName = (String) map.get("brandName");
        Integer brandId = null;
        if(map.get("brandId") != "" && map.get("brandId") != null){
            brandId = (Integer) map.get("brandId");
        }
        List<GoodsBrandEntity> goodsBrands=this.baseMapper.selectList(new LambdaQueryWrapper<GoodsBrandEntity>()
                                                .eq(GoodsBrandEntity::getBrandName,brandName)
                                                .eq(GoodsBrandEntity::getBrandId,brandId));
        if(goodsBrands == null || goodsBrands.size() == 0){
           return ResponseResult.success();
        }else{
            return ResponseResult.fail(BizCodeEnume.BRAND_NAME_ALREADY_EXISTS);
        }

    }

    @Override
    public ResponseResult deleteBrand(GoodsBrandDTO dto) {
        if (null != dto && null != dto.getToken()) {
            //校验token
            String token = dto.getToken();
            UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(token);
            if (null != userInfo) {
                Integer num = goodsCommonMapper.selectCount(new LambdaQueryWrapper<GoodsCommonEntity>().eq(GoodsCommonEntity::getBrandId,dto.getBrandId()));
                if (num > 0) {
                    return ResponseResult.fail(BizCodeEnume.BRAND_ASSOCIATED_GOODS);
                }
                //删除 品牌
                this.baseMapper.deleteById(dto.getBrandId());
                goodsBrandCatMapper.delete(new LambdaQueryWrapper<GoodsBrandCatEntity>().eq(GoodsBrandCatEntity::getBrandId,dto.getBrandId()));
                return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
            }
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        return ResponseResult.fail(BizCodeEnume.VALID_EXCEPTION);

    }

    @Override
    public ResponseResult updateBrand(GoodsBrandDTO dto) {

        if (null == dto.getShopId()) {
            dto.setShopId(0);
        }
        dto.setBrandEnable(1);
        dto.setBrandRecommend(1);
        dto.setBrandInitial(PinyinUtils.ToFirstChar2(dto.getBrandName()));
        Integer integer = this.baseMapper.selectCount(new LambdaQueryWrapper<GoodsBrandEntity>()
                         .eq(GoodsBrandEntity::getBrandName,dto.getBrandName())
                         .ne(GoodsBrandEntity::getBrandId, dto.getBrandId()));
        if (integer>0){
            return ResponseResult.fail(BizCodeEnume.BRAND_NAME_ALREADY_EXISTS);
        }
        if (null == dto.getBrandId()) {
            this.baseMapper.insertBrand(dto);

        } else {
            //修改品牌中间表
            goodsBrandCatMapper.updateBatchBrandCat(dto);

            goodsCommonMapper.update(null,new LambdaUpdateWrapper<GoodsCommonEntity>()
                                .eq(GoodsCommonEntity::getBrandId,dto.getBrandId())
                                .set(GoodsCommonEntity::getBrandName,dto.getBrandName()));

            this.baseMapper.updateBrand(dto);
        }

        return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
    }

    @Override
    public ResponseResult queryBrandList(GoodsBrandDTO dto) {
        try {
            if (null != dto && null != dto.getToken()) {
                //校验token
                String token = dto.getToken();
                UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(token);
                if (null != userInfo) {
                    //将对象转换为map
                    Map data = ParseMapUtils.beanToMap(dto);
                    //分页查询数据
                    IPage<GoodsBrandEntity> page = this.baseMapper.queryBrandList(new Query<GoodsBrandEntity>().getPage(data), dto);

                    return ResponseResult.success(PageUtils.getPage(page));
                }
                return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return ResponseResult.fail(BizCodeEnume.VALID_EXCEPTION);

    }

    @Override
    public ResponseResult queryGoodsBrandById(GoodsBrandDTO param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_SHOP_SETSHOP, param.getToken());

        if (userPermissionsResult.getFlag()) {
            // 查询品牌明细
            GoodsBrandEntity result = this.baseMapper.selectById(param.getBrandId());
            return ResponseResult.success(result);
        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
    }

    @Override
    public ResponseResult queryGoodsBrandList(GoodsBrandDTO param) {
        List<GoodsBrandEntity> results = new ArrayList<GoodsBrandEntity>();

        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_SHOP_SETSHOP, param.getToken());

        if (userPermissionsResult.getFlag()) {
            param.setShopId(Integer.valueOf(userPermissionsResult.getShopId()));
            // 查询品牌明细
            results = this.baseMapper.selectByShopId(param);
            // 设置分类名称
            for (GoodsBrandEntity result : results) {
                String catName = goodsCatMapper.selectById(result.getCatId()).getCatName();
                result.setCatName(catName);
            }

        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        return ResponseResult.success(results);
    }
}




